import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

Vue.use(Vuex);
// 登录验证
export default new Vuex.Store({
  state: {
    user: false,
    tabsList: [],
    nowTab: '',
    areaTree: [],
    basinOptions: []
  },
  mutations: {
    // 登录
    login(state, user) {
      state.user = user;
      localStorage.setItem("userInfo", user);
    },
    // 退出
    logout(state, user) {
      state.user = "";
      state.tabsList = [];
      localStorage.setItem("userInfo", "");
    },
    // add tab
    addTabs(state, tabItem) {
      console.log(tabItem)
      if (state.tabsList.length == 0) {
        state.tabsList = [tabItem]
      } else if (state.tabsList.filter(l => l.name == tabItem.name).length == 0) {
        state.tabsList.push(tabItem)
      }
      // state.nowTab = tabItem.name
    },
    // del tab
    delTab(state, name) {
      let index = 0
      for (let item of state.tabsList) {
        if (item.name == name) {
          break;
        }
        index++;
      }
        state.tabsList.splice(index, 1);
    },
    set_nowTab(state, val){
      state.nowTab = val
    },
    delAllTabs(state,val){
      state.tabsList = val ? [val] : []
    },

    set_areaTree(state, val) {
      state.areaTree = val
    },
    set_basinOptions(state, val) {
      state.basinOptions = val
    },
    get_areaTree(state) {
      return state.areaTree
    },
    get_basinOptions(state) {
      return state.basinOptions
    }
  },
  actions: {
    // 登录
    login({ commit }, user) {
      commit('login', user)
    },
    // 退出
    logout({ commit }, user) {
      commit('logout', user)
    },

    // setAreaTree({ commit }, areaTree) {
    //   commit('set_areaTree', areaTree)
    // }
  },
  plugins: [
    createPersistedState()
  ]
})